import { ActionIcon, Anchor, Avatar, Group, Indicator, Space, Table, Text, Tooltip } from '@mantine/core';
import { IconMail } from '@tabler/icons-preact';
import { Person } from '../../models/Persons';

function UsersByDepartment({ usersByDepartment, department }: { usersByDepartment: Person[], department: string }) {

	const rows = usersByDepartment.map(item => {

		return (
			<Table.Tr key={item.id}>
				<Table.Td>
					<Group gap="sm">
						<Tooltip label={item.missingInfo} disabled={!item.isMissing}>
							<Indicator size={12} offset={5} position="bottom-end" color="red" withBorder disabled={!item.isMissing}>
								<Avatar size={30} radius="lg" variant='light'>
									{item.name[0]}
								</Avatar>
							</Indicator>
						</Tooltip>
						<div>
							<Anchor fz="sm" fw={500} href={`/#/users/${item.id}`}>
								{item.name}
							</Anchor>
							<Text c="dimmed" fz="xs">
								{item.position}
							</Text>
						</div>
					</Group>
				</Table.Td>
				<Table.Td>
					<Text fz="sm">{item.workPhone && item.workPhone > 0 ? item.workPhone : null}</Text>
					<Text fz="xs">{item.cellPhone}</Text>
				</Table.Td>
				<Table.Td>
					<Group justify="flex-end">
						{item.mail &&
							<ActionIcon variant="subtle" >
								<Tooltip label="Написать письмо">
									<Anchor href={"mailto:" + item.mail}>
										<IconMail size={20} />
									</Anchor>
								</Tooltip>
							</ActionIcon>
						}
					</Group>
				</Table.Td>
			</Table.Tr>
		)
	});

	return (
		<Table.Tbody>
			<Text>{department}</Text>
			{rows}
			<Space h="xl" />
		</Table.Tbody>
	)
}

export default function UserList({ groups }: { groups: Record<string, Person[]> }) {

	const rows = Object.entries(groups).map(([department, persons]) => (
		<UsersByDepartment usersByDepartment={persons} department={department} />
	));

	return (
		<Table verticalSpacing="xs" striped highlightOnHover>
			{rows}
		</Table>
	);
}
